<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Db;

class Wechat extends Api
{

    protected $noNeedLogin = ['authorize', 'login', 'officialaccountservice'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 微信小程序授权
     */
    public function authorize()
    {
        if (!$this->request->isPost()) {
            $this->error(__('invalid request'));
        }

        $iv             = $this->request->post('iv');
        $des            = $this->request->post('encryptedData');
        $code           = $this->request->post('code');
        $apptype        = 'wechat_applet';
        $pId            = $this->request->post('share_id', 0);
        $app            = wechat_factory();
        $session        = $app->auth->session($code);
        $decryptedData  = $app->encryptor->decryptData($session->session_key, $iv, $des);
        $third          = Db::name('UserThird')->where([
            'platform'  => 'wechat',
            'apptype'   => $apptype,
            'openid'    => $session->openid
        ])->order('id ASC')->find();

        Db::startTrans();
        if (!$third) {
            $userId = $this->auth->isLogin() ? $this->auth->id : 0;
            if (!$userId) {
                if (
                    (
                        !($userId = Db::name('UserThird')->where(['platform' => 'wechat', 'apptype' => $apptype, 'openid' => $session->openid, 'user_id' => ['GT', 0]])->value('user_id'))
                        &&
                        !empty($session->unionid) && !($userId = Db::name('UserThird')->where(['platform' => 'wechat', 'unionid' => $session->unionid, 'user_id' => ['GT', 0]])->value('user_id'))
                    )
                    ||
                    (
                        empty($session->unionid)
                    )
                ) {
                    $username   = md5($session->openid);
                    $password   = '88888888';
                    $extend = [
                        'p_id'      => \app\common\model\User::where(['id' => intval($pId)])->value('id', 0),
                        'group_id'  => 1,
                        'nickname'  => !empty($decryptedData['nickName']) ? $decryptedData['nickName'] : '微信用户',
                        'avatar'    => !empty($decryptedData['avatarUrl']) ? $decryptedData['avatarUrl'] : '',
                        'gender'    => !empty($decryptedData['gender']) ? $decryptedData['gender'] : 0,
                        'birthday'  => date('Y-m-d', 0),
                        'bio'       => '此用户很懒，什么也没有说~',
                        'region_id' => 0
                    ];

                    if ($this->auth->register($username, $password, '', '', $extend)) {
                        $userId = $this->auth->id;
                    } else {
                        Db::rollback();
                        $this->error($this->auth->getError());
                    }
                }
            }

            $data = [
                'user_id'       => $userId,
                'platform'      => 'wechat',
                'apptype'       => $apptype,
                'unionid'       => !empty($session->unionid) ? $session->unionid : Db::name('UserThird')->where(['platform' => 'wechat', 'user_id' => $userId])->value('unionid', ''),
                'openname'      => !empty($decryptedData['nickName']) ? $decryptedData['nickName'] : '微信用户',
                'openid'        => $session->openid,
                'access_token'  => '',
                'session_key'   => $session->session_key,
                'createtime'    => time(),
            ];

            Db::name('UserThird')->insert($data);
        } else {
            Db::name('UserThird')->where(['id' => $third['id']])->update(['session_key' => $session->session_key]);
        }

        Db::commit();
        $this->success('', ['openid' => $session->openid, 'unionid' => $session->unionid]);
    }

    /**
     * 微信登录
     *
     * @ApiTitle    (微信登录)
     * @ApiMethod   (POST)
     * @ApiParams   (name="platform", type="string", required=true, description="平台")
     * @ApiParams   (name="openid", type="string", required=true, description="openid")
     * @ApiParams   (name="unionid", type="string", required=true, description="unionid")
     * @ApiParams   (name="apptype", type="string", required=false, description="类型")
     */
    public function login()
    {
        if (!$this->request->isPost()) {
            $this->error(__('invalid request'));
        }

        $apptype    = $this->request->post('apptype', 'wechat_applet');
        $where      = [
            'platform'  => $this->request->post('platform'),
            'openid'    => $this->request->post('openid'),
            'unionid'   => $this->request->post('unionid')
        ];

        if ($apptype) {
            $where['apptype'] = $apptype;
        }

        $third = Db::name('UserThird')->where($where)->order('id DESC')->find();
        if (!$third) {
            $this->error('未第三方授权');
        }

        if (!$this->auth->direct($third['user_id'])) {
            $error = $this->auth->getError();
            $this->error($error ? $error : '用户不存在');
        }

        $userInfo = $this->auth->getUserinfo();
        if ($userInfo['status'] != 'normal') {
            $this->error('账户已锁定');
        }

        $this->success('', ['userinfo' => $userInfo]);
    }

    /**
     * 获取分享二维码
     */
    public function shareqrcode()
    {
        $app    = wechat_factory('officialAccount');
        $result = $app->qrcode->temporary((string)$this->auth->id, 6 * 24 * 3600);
        $this->success('', array_merge((array)$result, ['down_url' => $app->qrcode->url($result->ticket)]));
    }

    /**
     * 微信公众号服务
     */
    public function officialaccountservice()
    {
        $app = wechat_factory('officialAccount');
        $app->server->push(function ($message) use ($app) {
            switch ($message->MsgType) {
                // 收到事件消息
                case 'event':
                    switch ($message->Event) {
                        // 取消关注
                        case 'unsubscribe':
                            $text = '您已取消关注公众号';
                            break;

                        // 除了取消关注都回复以下内容
                        default :
                            $text =
<<< TEXT2
您好，感谢您的关注
    废为宝回收是一家运营“互联网+废品回收”的生活类服务平台企业，专注于各类废品回收[爱心]
    公司通过互联网方式，运用微信公众号、小程序，致力于为企业级客户、商户（商场、超市、写字楼、学校、医院、快递等）、社区提供更正规、快速、高效的再生资源上门回收服务[拳头]
招募合伙人：18982680009
TEXT2;
                            $user       = $app->user->get($message->FromUserName);
                            $apptype    = 'wechat_official_accounts';
                            $where      = [
                                'platform'  => 'wechat',
                                'apptype'   => $apptype,
                                'openid'    => $user->openid
                            ];

                            $third = Db::name('UserThird')->where($where)->order('id ASC')->find();
                            if (!$third) {
                                Db::startTrans();
                                $userId = 0;
                                if (
                                    (
                                        !($userId = Db::name('UserThird')->where(['platform' => 'wechat', 'apptype' => $apptype, 'openid' => $user->openid, 'user_id' => ['GT', 0]])->value('user_id'))
                                        &&
                                        !empty($user->unionid) && !($userId = Db::name('UserThird')->where(['platform' => 'wechat', 'unionid' => $user->unionid, 'user_id' => ['GT', 0]])->value('user_id'))
                                    )
                                    ||
                                    (
                                        empty($user->unionid)
                                    )
                                ) {
                                    $username   = md5($user->openid);
                                    $password   = '88888888';
                                    $extend = [
                                        'p_id'      => \app\common\model\User::where(['id' => intval(!empty($user->qr_scene_str) ? $user->qr_scene_str : 0)])->value('id', 0),
                                        'group_id'  => 1,
                                        'nickname'  => !empty($user->nickname) ? $user->nickname : '微信用户',
                                        'avatar'    => !empty($user->headimgurl) ? $user->headimgurl : '',
                                        'gender'    => !empty($user->sex) ? $user->sex : 0,
                                        'birthday'  => date('Y-m-d', 0),
                                        'bio'       => '此用户很懒，什么也没有说~',
                                        'region_id' => 0
                                    ];

                                    if ($this->auth->register($username, $password, '', '', $extend)) {
                                        $userId = $this->auth->id;
                                    } else {
                                        Db::rollback();
                                        break;
                                    }
                                }

                                $data = [
                                    'user_id'       => $userId,
                                    'platform'      => 'wechat',
                                    'apptype'       => $apptype,
                                    'unionid'       => !empty($user->unionid) ? $user->unionid : Db::name('UserThird')->where(['platform' => 'wechat', 'user_id' => $userId])->value('unionid', ''),
                                    'openname'      => !empty($user->nickname) ? $user->nickname : '微信用户',
                                    'openid'        => $user->openid,
                                    'access_token'  => '',
                                    'session_key'   => '',
                                    'createtime'    => time(),
                                ];

                                Db::name('UserThird')->insert($data);
                                Db::commit();
                            }

                            break;
                    }

                    return $text;
                    break;
                // 收到文字消息
                case 'text':

                    return $message->Content;
                    break;
                // ... 其它消息
                default:
                    return '欢迎关注 废为宝公众号';
                    break;
            }
        });

        $response = $app->server->serve();
        $response->send(); // Laravel 里请使用：return $response;
    }
}